/*
 * Copyright (c) 2016-2017 by Colley
 * All rights reserved.
 */
package com.swak.frame.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;

import com.swak.frame.logger.SwakLoggerFactory;


/**
 * ClassName: NetUtils.java 
 * @Description: NetUtils 获取IP等信息
 * @author colley.ma
 * @date 2021年3月15日
 */
public class NetUtils {
	
	
	private static Logger logger = SwakLoggerFactory.getLogger(NetUtils.class);
	
	private static final String UNKNOWN="unknown";
	
	private NetUtils(){
		
	}
	
    public static String getIpStr() {
        InetAddress inetAddress = getIp();

        if (inetAddress != null) {
            return inetAddress.getHostAddress();
        }

        return UNKNOWN;
    }

    public static InetAddress getIp() {
        InetAddress ip = null;

        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();

            while (interfaces.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) interfaces.nextElement();
                Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();

                while (inetAddresses.hasMoreElements()) {
                    InetAddress inetAddress = inetAddresses.nextElement();

                    if (!inetAddress.isSiteLocalAddress() && !inetAddress.isLoopbackAddress()
                     && inetAddress.getHostAddress().indexOf(':') == -1) {
                        ip = inetAddress;
                        break;
                    }
                }
            }
        } catch (SocketException e) {
           logger.error("获取IP地址失败", e);
        }

        if (ip == null) {
            try {
                ip = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
               logger.error("获取本地IP地址失败", e);
            }
        }

        return ip;
    }

    public static String getClientIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");

        if ((ip == null) || (ip.length() == 0) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if ((ip == null) || (ip.length() == 0) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if ((ip == null) || (ip.length() == 0) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        if ((ip == null) || (ip.length() == 0) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("http_client_ip");
        }

        if ((ip == null) || (ip.length() == 0) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }

        // 如果是多级代理，那么取第一个ip为客户ip
        if ((ip != null) && (ip.indexOf(',') != -1)) {
            ip = ip.substring(ip.lastIndexOf(',') + 1, ip.length()).trim();
        }

        return ip;
    }

    public static String getUserAgent(HttpServletRequest request) {
        String userAgent = request.getHeader("user-agent");

        if (StringUtils.isBlank(userAgent)) {
        	userAgent = request.getHeader("User-Agent");
        }

        if (StringUtils.isBlank(userAgent)) {
        	userAgent = request.getHeader("USER-AGENT");
        }

        return userAgent;
    }

}
